package com.lalilu.remote

import java.math.BigInteger
import java.net.DatagramPacket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.NetworkInterface
import java.security.MessageDigest
import java.util.*

object NetUtils {

    fun getMac(): String? {
        val interfaces = NetworkInterface.getNetworkInterfaces()
        while (interfaces.hasMoreElements()) {
            interfaces.nextElement()
                ?.takeIf { !it.isLoopback && !it.isVirtual && !it.isPointToPoint && it.isUp }
                ?.hardwareAddress
                ?.apply {
                    return joinToString(":") { byte -> String.format("%02X", byte) }
                }
        }
        return null
    }

    fun isLocalHost(address: InetAddress): Boolean {
        return NetworkInterface.getNetworkInterfaces().toList().map { it.inetAddresses.toList() }.flatten()
            .any { it.hostAddress == address.hostAddress }
    }
}

private val md5Digest = MessageDigest.getInstance("MD5")

fun String.md5(): String {
    return md5Digest.run {
        reset()
        update(this@md5.toByteArray())
        BigInteger(1, digest()).toString(16).uppercase()
    }
}

fun String.toUdpPacket(address: String, port: Int): DatagramPacket {
    return toUdpPacket(InetSocketAddress(address, port))
}

fun String.toUdpPacket(address: InetSocketAddress): DatagramPacket {
    return toUdpPacket().also { it.socketAddress = address }
}

fun String.toUdpPacket(): DatagramPacket {
    return toByteArray().let { text -> DatagramPacket(text, text.size) }
}

fun isMacOS(): Boolean {
    val os = System.getProperty("os.name", "generic").lowercase(Locale.ENGLISH)
    return os.indexOf("mac") >= 0 || os.indexOf("darwin") >= 0
}

